define(['butterfly/notification', 'view!main/dialog/dialog'], function(Notification, Dialog) {

	var ModuleManager = function() {
		this.serverInfo = {
	      'appKey': '65995a05f3bdb7cf90bcab98f03b7b05',
	      'secret': '93f53d4c-d326-4268-af12-e08778b152ca'
	  }
	  this.platform = 'ios'
	  this.version = '1.0.1'
	  this.identifier = 'com.foreveross.atom'
	  this.serverUrl = 'http://localhost:3000';
	  // this.serverUrl = 'http://115.28.1.119:18860';
	}

	_.extend(ModuleManager.prototype, {

		storageDirectory: '/',

		wwwDirecotry: '/',

		getPrivellege: function(username, callback) {
      var url = this.serverUrl + "/mam/api/mam/clients/apps/" + this.identifier + "/" + username +"/auth?appKey=" + this.serverInfo.appKey;
      $.ajax({
        url: url,
        method: 'GET',
      }).success(function(data) {
        console.log(data);
        callback && callback(data);
      }).error(function() {

      });
    },

    isAllow: function(identifier, operation) {
    	if(!this.privellege) return false;
    	return _.find(this.privellege, function(p) {
    		return p[1] === identifier && p[0] == operation;
    	})
    },

		checkUpdate: function(success, fail) {
			console.log('check module update');
			var _this = this;
			var task = 2;
			var localModule, remoteModule;
			this.getLocalModulesInfo(function(modules) {
				localModule = modules
				--task == 0 && success(_this.diffModules(localModule, remoteModule))
			}, fail);

			this.getLastestModulesFromServer(function(modules) {
				remoteModule = modules
				--task == 0 && success(_this.diffModules(localModule, remoteModule))
			}, fail)

		},

		fs: function(action, data, callback) {
			var me = this;
			$.ajax({
				method: data.type || 'GET',
				url: this.serverUrl + "/fs/" + action,
				data: {
					path: data.path
				}
			}).success(callback)
		},
		// 获取本地模块信息
		getLocalModulesInfo: function(success, fail) {
			console.log('获取本地模块');
			var _this = this;
			var packagesPath = []
			var localModule = []
			var count = 0;
			var root = this.wwwDirecotry
			var filesToCheck = 0;

			this.fs('readdir', {path: root}, function(obj) {
				var files = obj[1];
				filesToCheck = files.length;
				files.forEach(function(file) {
					_this.fs('stat', {path: root + file}, function(obj) {
						if(obj.isDirectory) {
							// console.log(file)
							_this.fs('exists', {path: root + file + '/package.json'}, function(obj) {
								if(obj[0] == true) {
									packagesPath.push(root + file + '/package.json');
								} else { // 兼容CubeModule.json modify by hyw
									_this.fs('exists', {path: root + file + '/CubeModule.json'}, function(obj) {
										if(obj[0] == true) {
											packagesPath.push(root + file + '/CubeModule.json');
										}
									});
								}
							})
						}
						-- filesToCheck == 0 && readPackageJson()
					});
				});
			});

			function readPackageJson() {
				setTimeout(function() {
					var count = packagesPath.length;
					packagesPath.forEach(function(path) {
						_this.fs('readFile', {path: path}, function(obj) {
							var p = JSON.parse(obj.data)
							p.build && localModule.push(p);
							--count == 0 && success(localModule)
						})
					})
				}, 2000);
			}

		},

		getLastestModulesFromServer: function(success, fail) {
			console.log('获取服务器最新模块');
			var _this = this;
			this.getAppTokenFromServer(function(token) {
				_this.getModulesInfoFromServer(token, success, fail);
			})
		},


		getAppTokenFromServer: function(success, fail) {
			console.log('获取应用Token');
			var url = this.serverUrl + '/mam/api/mam/clients/apps/' + this.platform + '/'  + this.identifier + '/'  + this.version + '/'  + 'validate'
			$.ajax({
				url: url,
				method: 'POST',
				data: this.serverInfo
			}).success(function(data) {
				success && success(data.token)
			}).error(fail)
		},

		getModulesInfoFromServer: function(token, success, fail) {
			console.log('获取服务器模块');
			var token = token || this.token;
			var url = this.serverUrl + '/mam/api/mam/clients/apps/modules/' + token;
			$.ajax({
				url: url,
				method: "GET",
				data: {timeStamp: new Date().getTime()},
			}).success(function(data) {
				success && success(data.modules);
			});
		},

		diffModules: function(local, remoteModules) {
			var diff = []
			var localModulesMapping = _.object(_.map(local, function(module) {
				return module.identifier
			}), local)

			var updatableModuleArray = _.filter(remoteModules, function(remoteModule) {
	      //根据远程模块的identifier，尝试找出相应的本地模块
	      var localModule = localModulesMapping[remoteModule.identifier];
	      //有同样identifier的本地模块存在，且版本号不相同，返回远程模块信息。
	      return localModule && (localModule.version < remoteModule.version) || !localModule;
	    });
	    return updatableModuleArray;

		},

		downloadModules: function(modulesArray, callback) {
			var _this = this;
			modulesArray.forEach(function(module) {
				// var url = _this.serverUrl + path.join('/mam/api/mam/clients/files/', module.bundle) + '?appkey=' + this.identifier;
				// request(url).pipe(fs.createWriteStream(path.join(_this.wwwDirecotry, module.identifier + '.zip')))
				$.ajax({
					method: 'GET',
					url: _this.serverUrl + '/fs/download/' + module.bundle,
					data: {
						appkey: _this.serverInfo.appKey,
						identifier: module.identifier
					}
				}).success(function(obj) {
					if(obj == 'ok') {
						callback('success');
						new Notification({
							type: 'info',
							message: '模块下载完成'
						}).show();
					} else {
						callback('fail');
					}
				});
			})
		},

		deleteModel: function(identifier, callback) {
			if(!this.isAllow(identifier, 'DELETE')) {
				return new Notification({
					message: '当前模块无权限卸载',
					type: 'error'
				}).show();
			}

			var _this = this;

			new Dialog({
				ok: request,
				message: "你确定要删除当前模块吗?"
			}).show();

			function request() {
				$.ajax({
					method: 'GET',
					url: _this.serverUrl + '/fs/rmdir',
					data: {
						path: identifier
					}
				}).success(function(data) {
					if(data.result) {
						callback && callback();
					}
				}).error(function() {

				});
			}
		}

	});

	return ModuleManager;
})


// module.exports = ModuleManager
